<!-- src/views/account/Profile.vue -->
<template>
  <div class="profile-container">
    <h2>个人信息</h2>
    <el-card class="profile-card">
      <div class="avatar-section">
        <el-avatar
            :src="avatarUrl"
            :size="80"
            @error="handleAvatarError"
        />
        <el-button v-if="isEditing" type="primary" size="small" @click="changeAvatar" class="change-avatar-btn">
          更换头像
        </el-button>
        <el-button v-else type="primary" size="small" @click="changeAvatar" class="change-avatar-btn">
          查看大图
        </el-button>

        <!-- 隐藏的头像上传输入框 -->
        <input
            ref="avatarInputRef"
            type="file"
            accept="image/jpeg,image/png"
            style="display: none"
            @change="handleAvatarFileChange"
        />
      </div>

      <el-form :model="profileForm" label-width="120px" ref="formRef">
        <el-form-item label="用户ID">
          <el-input v-model="profileForm.userId" disabled />
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="profileForm.name" :disabled="!isEditing" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="profileForm.email" :disabled="!isEditing" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="profileForm.mobile" :disabled="!isEditing" />
        </el-form-item>
        <el-form-item label="用户类型">
          <el-tag :type="getUserTypeTag(profileForm.userType)">
            {{ getUserTypeName(profileForm.userType) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="认证状态">
          <el-tag :type="getAuthStatusTag(profileForm.authStatus)">
            {{ getAuthStatusName(profileForm.authStatus) }}
          </el-tag>
          <el-button
              v-if="profileForm.authStatus === 'NOT_SUBMITTED' || profileForm.authStatus === 'REJECTED'"
              type="primary"
              size="small"
              @click="showAuthDialog"
              style="margin-left: 10px;"
          >
            实名认证
          </el-button>
        </el-form-item>

        <div v-if="profileForm.authInfo && (profileForm.authStatus === 'VERIFIED' || profileForm.authStatus === 'PENDING')">
          <h3>认证信息</h3>
          <el-form-item label="真实姓名">
            <el-input v-model="profileForm.authInfo.realName" disabled />
          </el-form-item>
          <el-form-item label="身份证号">
            <el-input v-model="profileForm.authInfo.idCard" disabled />
          </el-form-item>
          <div v-if="profileForm.authInfo.idCardFront || profileForm.authInfo.idCardBack" class="id-card-images">
            <el-form-item label="身份证正面">
              <el-image
                  v-if="profileForm.authInfo.idCardFront"
                  :src="idCardFrontUrl"
                  :preview-src-list="[idCardFrontUrl]"
                  fit="cover"
                  style="width: 150px; height: 100px;"
              />
            </el-form-item>
            <el-form-item label="身份证反面">
              <el-image
                  v-if="profileForm.authInfo.idCardBack"
                  :src="idCardBackUrl"
                  :preview-src-list="[idCardBackUrl]"
                  fit="cover"
                  style="width: 150px; height: 100px;"
              />
            </el-form-item>
          </div>
        </div>

        <el-form-item>
          <el-button v-if="!isEditing" type="primary" @click="startEdit">编辑信息</el-button>
          <div v-else>
            <el-button type="primary" @click="saveProfile" :loading="saving">保存</el-button>
            <el-button @click="cancelEdit" style="margin-left: 10px;">取消</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 实名认证对话框 -->
    <el-dialog
        v-model="authDialogVisible"
        title="实名认证"
        width="500px"
        :before-close="handleAuthDialogClose"
    >
      <el-form
          :model="authForm"
          :rules="authRules"
          ref="authFormRef"
          label-width="100px"
      >
        <el-form-item label="真实姓名" prop="realName">
          <el-input
              v-model="authForm.realName"
              placeholder="请输入真实姓名"
          />
        </el-form-item>

        <el-form-item label="身份证号" prop="idCard">
          <el-input
              v-model="authForm.idCard"
              placeholder="请输入身份证号"
          />
        </el-form-item>

        <el-form-item label="身份证正面" prop="idCardFront">
          <div class="upload-area">
            <el-upload
                class="id-card-uploader"
                :action="uploadUrl"
                :show-file-list="false"
                :on-success="(response) => handleUploadSuccess(response, 'idCardFront')"
                :on-error="handleUploadError"
                :before-upload="beforeUpload"
            >
              <img v-if="authForm.idCardFront" :src="authForm.idCardFront" class="id-card-image" />
              <el-icon v-else class="id-card-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <div class="upload-tip">点击上传身份证正面照片</div>
          </div>
        </el-form-item>

        <el-form-item label="身份证反面" prop="idCardBack">
          <div class="upload-area">
            <el-upload
                class="id-card-uploader"
                :action="uploadUrl"
                :show-file-list="false"
                :on-success="(response) => handleUploadSuccess(response, 'idCardBack')"
                :on-error="handleUploadError"
                :before-upload="beforeUpload"
            >
              <img v-if="authForm.idCardBack" :src="authForm.idCardBack" class="id-card-image" />
              <el-icon v-else class="id-card-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <div class="upload-tip">点击上传身份证反面照片</div>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleAuthDialogClose">取消</el-button>
          <el-button type="primary" @click="submitAuth" :loading="authSubmitting">提交认证</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { UserApi } from '@/api/user/index.js'

// 默认头像路径
const defaultAvatar = '/default-avatar.png'

const profileForm = ref({
  userId: '',
  name: '',
  avatar: '',
  mobile: '',
  email: '',
  userType: '',
  authStatus: '',
  authInfo: {
    realName: '',
    idCard: '',
    idCardFront: '',
    idCardBack: ''
  }
})

const originalProfile = ref({}) // 保存原始数据用于取消编辑
const isEditing = ref(false)
const saving = ref(false)
const formRef = ref(null)

// 实名认证相关
const authDialogVisible = ref(false)
const authFormRef = ref(null)
const authSubmitting = ref(false)

const authForm = reactive({
  realName: '',
  idCard: '',
  idCardFront: '',
  idCardBack: ''
})

// 头像上传相关
const avatarInputRef = ref(null)
const avatarUploading = ref(false)

// 上传URL（示例，实际应替换为真实的上传接口）
const uploadUrl = '/api/upload' // 示例URL，需要替换为实际的文件上传接口

// 表单验证规则
const authRules = {
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度应在2-20位之间', trigger: 'blur' }
  ],
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    {
      pattern: /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[0-9Xx]$/,
      message: '身份证号格式不正确',
      trigger: 'blur'
    }
  ],
  idCardFront: [
    { required: true, message: '请上传身份证正面照片', trigger: 'change' }
  ],
  idCardBack: [
    { required: true, message: '请上传身份证反面照片', trigger: 'change' }
  ]
}

// 计算属性：处理头像URL
const avatarUrl = computed(() => {
  // 如果没有头像数据，使用默认头像
  if (!profileForm.value.avatar) {
    return defaultAvatar
  }

  // 如果已经是完整URL（http或https开头），直接返回
  if (profileForm.value.avatar.startsWith('http://') || profileForm.value.avatar.startsWith('https://')) {
    return profileForm.value.avatar
  }

  // 如果是相对路径，添加基础URL
  const baseUrl = import.meta.env.VITE_API_BASE_URL || ''

  // 确保路径格式正确
  let avatarPath = profileForm.value.avatar
  if (!avatarPath.startsWith('/')) {
    avatarPath = '/' + avatarPath
  }

  // 如果有基础URL，拼接完整路径；否则直接返回路径
  return baseUrl ? baseUrl + avatarPath : avatarPath
})

// 计算属性：处理身份证正面URL
const idCardFrontUrl = computed(() => {
  if (!profileForm.value.authInfo?.idCardFront) {
    return ''
  }

  // 如果已经是完整URL，直接返回
  if (profileForm.value.authInfo.idCardFront.startsWith('http://') ||
      profileForm.value.authInfo.idCardFront.startsWith('https://')) {
    return profileForm.value.authInfo.idCardFront
  }

  // 如果是相对路径，添加基础URL
  const baseUrl = import.meta.env.VITE_API_BASE_URL || ''
  let imagePath = profileForm.value.authInfo.idCardFront
  if (!imagePath.startsWith('/')) {
    imagePath = '/' + imagePath
  }

  return baseUrl ? baseUrl + imagePath : imagePath
})

// 计算属性：处理身份证反面URL
const idCardBackUrl = computed(() => {
  if (!profileForm.value.authInfo?.idCardBack) {
    return ''
  }

  // 如果已经是完整URL，直接返回
  if (profileForm.value.authInfo.idCardBack.startsWith('http://') ||
      profileForm.value.authInfo.idCardBack.startsWith('https://')) {
    return profileForm.value.authInfo.idCardBack
  }

  // 如果是相对路径，添加基础URL
  const baseUrl = import.meta.env.VITE_API_BASE_URL || ''
  let imagePath = profileForm.value.authInfo.idCardBack
  if (!imagePath.startsWith('/')) {
    imagePath = '/' + imagePath
  }

  return baseUrl ? baseUrl + imagePath : imagePath
})

// 头像加载错误处理
const handleAvatarError = () => {
  console.log('头像加载失败，使用默认头像')
  profileForm.value.avatar = defaultAvatar
}

// 获取用户信息
const fetchProfile = async () => {
  try {
    console.log('开始获取用户信息...')
    const res = await UserApi.getUserInfo()
    console.log('获取到的用户信息:', res.data)

    profileForm.value = res.data

    // 调试信息：检查头像URL
    console.log('头像URL:', profileForm.value.avatar)
    console.log('处理后的头像URL:', avatarUrl.value)

    // 保存原始数据副本
    originalProfile.value = JSON.parse(JSON.stringify(res.data))
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败: ' + error)
  }
}

// 开始编辑
const startEdit = () => {
  isEditing.value = true
}

// 保存个人信息
const saveProfile = async () => {
  saving.value = true
  try {
    // 准备要更新的数据
    const updateData = {
      name: profileForm.value.name,
      avatar: profileForm.value.avatar,
      email: profileForm.value.email,
      mobile: profileForm.value.mobile
    }

    console.log('发送到后端的数据:', updateData)

    const res = await UserApi.updateUserProfile(updateData)
    ElMessage.success('个人信息更新成功')
    isEditing.value = false
    originalProfile.value = JSON.parse(JSON.stringify(profileForm.value))
  } catch (error) {
    console.error('更新失败:', error)
    ElMessage.error('更新失败: ' + error)
  } finally {
    saving.value = false
  }
}

// 取消编辑
const cancelEdit = () => {
  // 恢复原始数据
  profileForm.value = JSON.parse(JSON.stringify(originalProfile.value))
  isEditing.value = false
}

// 用户类型映射
const getUserTypeName = (type) => {
  const typeMap = {
    'PUBLIC': '公众用户',
    'LAWYER': '律师用户',
    'ADMIN': '管理员'
  }
  return typeMap[type] || type
}

// 用户类型标签样式
const getUserTypeTag = (type) => {
  const tagMap = {
    'PUBLIC': 'success',
    'LAWYER': 'warning',
    'ADMIN': 'danger'
  }
  return tagMap[type] || 'info'
}

// 认证状态映射
const getAuthStatusName = (status) => {
  const statusMap = {
    'NOT_SUBMITTED': '未提交',
    'PENDING': '审核中',
    'VERIFIED': '已认证',
    'REJECTED': '已拒绝'
  }
  return statusMap[status] || status
}

// 认证状态标签样式
const getAuthStatusTag = (status) => {
  const tagMap = {
    'NOT_SUBMITTED': 'info',
    'PENDING': 'warning',
    'VERIFIED': 'success',
    'REJECTED': 'danger'
  }
  return tagMap[status] || 'info'
}

// 更换头像
const changeAvatar = () => {
  if (isEditing.value) {
    // 在编辑模式下，触发头像上传
    avatarInputRef.value.click()
  } else {
    // 在查看模式下，可以查看大图
    ElMessage.info('查看头像大图功能待开发')
  }
}

// 处理头像文件选择
const handleAvatarFileChange = (event) => {
  const file = event.target.files[0]
  if (file) {
    // 验证文件
    if (!beforeAvatarUpload(file)) {
      // 清空input值以便下次选择同一文件也能触发change事件
      event.target.value = ''
      return
    }

    // 创建FormData对象
    const formData = new FormData()
    formData.append('file', file)

    // 上传头像
    uploadAvatar(formData)
  }
  // 清空input值以便下次选择同一文件也能触发change事件
  event.target.value = ''
}

// 上传头像到服务器
const uploadAvatar = async (formData) => {
  avatarUploading.value = true
  try {
    // 调用实际的API接口上传头像
    const res = await UserApi.uploadAvatar(formData)
    if (res.data) {
      // 更新头像URL
      profileForm.value.avatar = res.data.url || res.data
      ElMessage.success('头像上传成功')
      console.log('上传后的头像URL:', profileForm.value.avatar)
    }
  } catch (error) {
    console.error('头像上传失败:', error)
    ElMessage.error('头像上传失败: ' + (error.message || error))
  } finally {
    avatarUploading.value = false
  }
}

// 头像上传前检查
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('上传头像只能是 JPG/PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传头像大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}

// 显示实名认证对话框
const showAuthDialog = () => {
  // 如果已有认证信息，预填充表单
  if (profileForm.value.authInfo) {
    authForm.realName = profileForm.value.authInfo.realName || ''
    authForm.idCard = profileForm.value.authInfo.idCard || ''
    authForm.idCardFront = profileForm.value.authInfo.idCardFront || ''
    authForm.idCardBack = profileForm.value.authInfo.idCardBack || ''
  }
  authDialogVisible.value = true
}

// 关闭实名认证对话框
const handleAuthDialogClose = () => {
  authDialogVisible.value = false
  // 重置表单
  if (authFormRef.value) {
    authFormRef.value.resetFields()
  }
  authForm.realName = ''
  authForm.idCard = ''
  authForm.idCardFront = ''
  authForm.idCardBack = ''
}

// 提交实名认证
const submitAuth = async () => {
  if (!authFormRef.value) return

  await authFormRef.value.validate(async (valid) => {
    if (valid) {
      authSubmitting.value = true
      try {
        const requestData = {
          realName: authForm.realName,
          idCard: authForm.idCard,
          idCardFront: authForm.idCardFront,
          idCardBack: authForm.idCardBack
        }

        const res = await UserApi.submitUserAuth(requestData)
        ElMessage.success('实名认证已提交，等待审核')

        // 关闭对话框
        handleAuthDialogClose()

        // 重新获取用户信息更新认证状态
        await fetchProfile()
      } catch (error) {
        ElMessage.error(error.message || '认证提交失败')
      } finally {
        authSubmitting.value = false
      }
    } else {
      ElMessage.error('请检查表单填写是否正确')
    }
  })
}

// 上传前检查
const beforeUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('上传图片只能是 JPG/PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}

// 上传成功处理
const handleUploadSuccess = (response, field) => {
  if (response && response.data) {
    authForm[field] = response.data.url || response.data
    ElMessage.success('上传成功')
  }
}

// 上传失败处理
const handleUploadError = (error) => {
  ElMessage.error('上传失败: ' + error)
}

onMounted(() => {
  fetchProfile()
})
</script>

<style scoped>
.profile-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
}

.profile-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 30px;
}

.change-avatar-btn {
  margin-top: 15px;
}

h3 {
  margin-top: 30px;
  margin-bottom: 15px;
  border-left: 4px solid #409eff;
  padding-left: 10px;
}

.id-card-images {
  display: flex;
  gap: 20px;
}

.upload-area {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.id-card-uploader .id-card-image {
  width: 178px;
  height: 178px;
  display: block;
}

.id-card-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.id-card-uploader .el-upload:hover {
  border-color: #409eff;
}

.id-card-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.upload-tip {
  margin-top: 10px;
  font-size: 12px;
  color: #999;
}

:deep(.el-form-item__content) {
  display: flex;
  align-items: center;
}

:deep(.el-button) {
  min-width: 100px;
}
</style>
